#include "buffer.h"

sem_t mutex;
int inicio, fim;
int tam_buffer;

Requisicao *buffer;

sem_t sem_buffer;

void inicia_buffer(int n_slaves){
	tam_buffer = 2*n_slaves+2;
	buffer = (Requisicao *) malloc(tam_buffer*sizeof(Requisicao));
	sem_init(&mutex, 1, 1);
	sem_init(&sem_buffer, 1, 0);
}


void buffer_push(Requisicao req){
	sem_wait(&mutex);
	fim=(fim+1)%tam_buffer;
	buffer[fim] = req;
	sem_post(&mutex);
	sem_post(&sem_buffer);
}

Requisicao buffer_pop(){
	sem_wait(&sem_buffer);
	sem_wait(&mutex);
	Requisicao req = buffer[inicio];
	inicio=(inicio+1)%tam_buffer;
	sem_post(&mutex);
	return req;
}

void freeBuffer(){
	if(buffer!=NULL)
		free(buffer);
}
